package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    //线程池
    private static final ExecutorService es = Executors.newFixedThreadPool(10);


    @Override
    public Result queryById(Long id) {
        //return Result.ok(queryWithLogicDelete(id));
        return Result.ok(cacheClient.getWithLogicDelete("shop:status", id, Shop.class, 10L, new Function<Long, Shop>() {
            @Override
            public Shop apply(Long aLong) {
                return getById(id);
            }
        }));
    }

    //使用缓存空对象解决店铺查询时缓存穿透
    private Shop queryWithPassThrough(Long id) {
        //1.从redis中查询缓存
        String s = stringRedisTemplate.opsForValue().get("shop:status" + id);
        if (StrUtil.isNotBlank(s)) {
            //2.存在，直接返回
            Shop shop = JSONUtil.toBean(s, Shop.class);
            return shop;
        }
        if (s != null) {
            //查到的缓存是空值
            return null;
        }
        //3.不存在，到数据库中查询
        Shop result = getById(id);

        if (result == null) {
            //4.不存在，返回错误
            stringRedisTemplate.opsForValue().set("shop:status" + id, "");
            return null;
        }
        //5.存在，写入redis并返回

        stringRedisTemplate.opsForValue().set("shop:status" + id, JSONUtil.toJsonStr(result), 2, TimeUnit.MINUTES);
        //saveShop2Redis(id,10L);
        return result;
    }

    //使用互斥锁解决缓存击穿
    private Shop queryWithMutex(Long id) {
        //1.从redis中查询缓存
        String s = stringRedisTemplate.opsForValue().get("shop:status" + id);

        if (StrUtil.isNotBlank(s)) {
            //2.存在，直接返回
            return JSONUtil.toBean(s, Shop.class);
        }
        if (s != null) {
            return null;
        }
        //3.不存在
        //4.尝试获取锁
        Shop result = null;
        try {
            boolean isLock = tryGetLock(id);
            if (!isLock) {
                //4.1没有获取到锁
                //休眠一段时间后再次获取锁
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //4.2获取到了锁

            //4.3获取到锁后，再次检查缓存中是否有对应的数据
            s = stringRedisTemplate.opsForValue().get("shop:status" + id);
            if (StrUtil.isNotBlank(s)) {
                //2.存在，直接返回
                return JSONUtil.toBean(s, Shop.class);
            }
            if (s != null) {
                return null;
            }
            //4.4再次检查缓存中无数据，查询数据库
            result = getById(id);

            if (result == null) {
                stringRedisTemplate.opsForValue().set("shop:status" + id, "");
                return null;
            }
            //5.存在，写入redis并返回
            stringRedisTemplate.opsForValue().set("shop:status" + id, String.valueOf(result), 2, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //6.释放锁
            unlock(id);
        }
        return result;
    }

    //使用逻辑删除解决缓存击穿
    private Shop queryWithLogicDelete(Long id) {
        //1.从redis中查询缓存
        String cache = stringRedisTemplate.opsForValue().get("shop:status" + id);
        if (StrUtil.isBlank(cache)) {
            //没查到，直接返回
            return null;
        }
        //2.查到了，需要判断缓存是否过期
        RedisData redisData = JSONUtil.toBean(cache, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);

        if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {
            //3.缓存未过期，直接返回
            return shop;
        }
        //4.缓存已过期,尝试获取锁
        boolean isLock = tryGetLock(id);
        if (isLock) {
            //6.获取锁成功
            String newCache = stringRedisTemplate.opsForValue().get("shop:status" + id);
            RedisData newRedisData = JSONUtil.toBean(newCache, RedisData.class);
            if (newRedisData.getExpireTime().isAfter(LocalDateTime.now())) {
                //获取锁成功后，缓存没有过期，直接返回
                //8.缓存没过期，直接返回缓存
                return JSONUtil.toBean((JSONObject) newRedisData.getData(), Shop.class);
            }
            //7.缓存过期，新建线程进行缓存重建
            es.submit(() -> {
                try {
                    this.saveShop2Redis(id, 20L);
                    //9.释放锁
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(id);
                }
            });
        }
        //5.获取锁失败，直接返回旧的缓存
        return shop;
    }


    //缓存重建
    private void saveShop2Redis(Long id, Long expireSeconds) {
        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set("shop:status" + id, JSONUtil.toJsonStr(redisData));
    }

    private boolean tryGetLock(Long id) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent("lock:shop:" + id, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(Long id) {
        stringRedisTemplate.delete("lock:shop:" + id);
    }

    @Override
    public Result update(Shop shop) {
        //先更新数据库
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        this.updateById(shop);
        //再删除缓存
        stringRedisTemplate.delete("shop:status" + id);
        return Result.ok();
    }

    @Override
    public Result queryNearShops(Integer typeId, Integer current, Double x, Double y) {
        //查询前端是否传递了地理坐标
        if (x == null || y == null) {
            //没有传递地理坐标，不需要查询附近的店铺
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }

        //计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        String key = "shop:geo:" + typeId;
        //查到的结果是shopId， distance
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(key,
                //确定圆心
                GeoReference.fromCoordinate(x, y),
                //确定半径,默认单位为米
                new Distance(5000),
                //查询结果需要带上到圆心的距离
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance()
                        //limit默认从第一条数据查到end
                        .limit(end)
        );

        //开始截取数据
        if(results == null){
            return Result.ok(Collections.EMPTY_LIST);
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if(list.size()<=from){
            //查询到的数据都是上一页的数据
            return Result.ok(Collections.EMPTY_LIST);
        }
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result->{
            //获取店铺id
            String shopId = result.getContent().getName();
            ids.add(Long.valueOf(shopId));
            //获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopId, distance);
        });
        //根据id查询数据库
        String idStr = StrUtil.join(",", ids);
        List<Shop> shopList = query().in("id", ids).last("order by filed (id," + idStr + ")").list();
        for (Shop shop : shopList) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shopList);
    }
    //ToDO 无符号右移和有符号右移，与运算
}
